# LuckPay Web Manage System
#
# Copyright (c) 2016 Lucky Byte, Inc.
#
express = require 'express'
pgsql   = require 'pg'
router = express.Router()
module.exports = router

router.all '/', (req, res, next) ->
    where_clause = """(
        serial::text like $1 or acqu_id like $1 or fowd_id like $1 or
        trace_num like $1 or pri_acct like $1 or trans_amt like $1 or
        term_id like $1 or acpt_id like $1 or retref_num like $1 or
        fowd_settl like $1 or acqu_settl like $1 or order_id like $1
    )"""

    # 如果没有提供清算日期，则查询昨日
    settl_date = req.body.settl_date or req.query.settl_date or \
        moment().subtract(1, 'd').format('YYYY-MM-DD')

    where_clause += """
        and year = #{settl_date.substring(0, 4)}
        and settl_date = '#{settl_date.substring(5,7) + settl_date.substring(8,10)}'
    """
    res.locals.settl_date = settl_date

    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err)

    # 查询记录总数
    await client.query \
        "select count(*) as count from upay_acoma where #{ where_clause }", [
            '%' + res.locals.keyword + '%'
        ], defer err, result
    if err then done(client); return next(err)
    res.locals.total = result.rows[0].count

    # 查询当前页面中显示的记录
    await client.query \
        "select * from upay_acoma where #{ where_clause }
            order by serial desc
            offset $2::int limit $3::int", [
            '%' + res.locals.keyword + '%'
            res.locals.offset, res.locals.page_rows
        ], defer err, result
    if err then done(client); return next(err)
    done()

    # 省略账号的中间部分
    fmt_pan = (pri_acct) ->
        if not pri_acct or pri_acct.length < 9
            return pri_acct
        len = pri_acct.length
        pri_acct = pri_acct.substring(0, 4) + ' .. ' +
            pri_acct.substring(len - 4, len)

    # 获取主账号
    for record in result.rows
        record.pri_acct = fmt_pan(record.pri_acct)

    res.render 'upay/acoma/index', records: result.rows
